/*
 * Copyright (c) 2017, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.wsonrpc.core;

import net.apexes.wsonrpc.json.JsonRpcRequest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
class ServiceMethodInvoker {

    private final Object instance;
    private final Set<Method> methods;

    ServiceMethodInvoker(Object instance, Set<Method> methods) {
        this.instance = instance;
        this.methods = methods;
    }

    public Object invoke(JsonRpcRequest request) throws ParamException, InvocationTargetException, IllegalAccessException {
        Object[] args = null;
        Method method = null;
        for (Method m : methods) {
            if (m.getParameterTypes().length != request.getParamCount()) {
                continue;
            }
            Object[] params = request.getParams(m.getGenericParameterTypes());
            if (params != null) {
                method = m;
                args = params;
                break;
            }
        }
        if (method == null) {
            throw new ParamException();
        }

        return method.invoke(instance, args);
    }

    /**
     * @author hedyn
     */
    static class ParamException extends Exception {
    }

}
